package org.gongliang.jsmile.authc.sys.service;

import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.gongliang.jsmile.authc.sys.dao.SysLogDao;
import org.gongliang.jsmile.authc.sys.entity.SysLog;
import org.gongliang.jsmile.common.base.CRUDService;
import org.gongliang.jsmile.common.kit.web.SpringKit;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
* 
* @author 龚亮
* @version 1.0
* @date 2018年08月25日 04:57:24
*/
@Service
public class SysLogService extends CRUDService<SysLogDao, SysLog> {

	private static final Logger logger = LoggerFactory.getLogger(SysLogService.class);

	public boolean saveBatch(List<SysLog> logs) {
		SqlSessionTemplate sqlSessionTemplate = SpringKit.getBean(SqlSessionTemplate.class);
		SqlSession sqlSession = null;
		int result = 1;
		try {
			sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			int batchCount = 1000;
			int lastBatchCount = batchCount;
			if (logs != null && logs.size() > 0) {
				for (int index = 0; index < logs.size(); index++) {
					if (lastBatchCount >= logs.size()) {
						lastBatchCount = logs.size();
						result = result * sqlSession.insert("org.gongliang.jsmile.authc.sys.dao.SysLogDao.batchSave",
								logs.subList(index, lastBatchCount));
						sqlSession.commit();
						break;
					} else {
						result = result * sqlSession.insert("org.gongliang.jsmile.authc.sys.dao.SysLogDao.batchSave",
								logs.subList(index, lastBatchCount));
						sqlSession.commit();
						index = lastBatchCount;
						lastBatchCount = index + (batchCount - 1);
					}
				}
				sqlSession.commit();
			}
		} catch (Exception e) {
			logger.error("批量插入日志失败:" + ExceptionUtils.getStackTrace(e));
		} finally {
			sqlSession.close();
		}
		return retBool(result);
	}
	
}
